/**
* ==================================================
 *  @file BasicDoubleLinkList.c
 *  @desc 双链表的基本操作
 *  @author WangBlue(wangjiping596@gmail.com)
 *  @date 2025-07-20 10:39
 *  @version 1.0
 */

#include <complex.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int data;
    struct node *next;
    struct node *pre;
}node, *link;

// 创建节点
link createNode (int value) {
    link newNode = (link) malloc(sizeof (node));
    if (newNode == NULL) return NULL;
    newNode->data= value;
    newNode->next = NULL;
    newNode->pre  = NULL;
    return newNode;
}

void initNode(link *head) {
    link newNode = createNode(0);
    if (newNode == NULL) return;
    *head = newNode;
}

// 头部插入
void insertHead(link head, int value) {
    link newNode = createNode(value);
    if (newNode == NULL) return;
    newNode->pre = head;
    newNode->next = head->next;
    if (head->next != NULL) {
        head->next->pre = newNode;
    }
    head->next = newNode;
}

// 尾部插入
void insertTail(link head, int value) {
    link cur = head;
    while (cur->next != NULL) {
        cur = cur->next;
    }
    link newNode = createNode(value);
    if (newNode == NULL) return;
    cur->next = newNode;
    newNode->pre = cur;
}

// 打印链表
void printList(link head) {
    if (head == NULL || head->next == NULL) return;
    link cur = head->next;
    while (cur != NULL) {
        printf("value is %d\n", cur->data);
        cur = cur->next;
    }
    printf("\n");
}

// 得到链表长度
int getLength(link head) {
    int lenght = 0;
    if (head == NULL || head->next == NULL) return 0;
    link cur = head->next;
    while (cur != NULL) {
        cur = cur->next;
        lenght++;
    }
    return lenght;
}

// 在指定位置插入（带头节点，pos 从 1 开始，插入到第 pos 个位置）
void insertByPos(link head, int value, int pos) {
    if (pos < 1 || head == NULL) return;

    link cur = head;
    int index = 0;

    // 遍历到第 pos-1 个节点
    while (cur != NULL && index < pos - 1) {
        cur = cur->next;
        index++;
    }

    // 如果 cur == NULL，说明 pos 超过链表长度 + 1
    if (cur == NULL) return;

    link newNode = createNode(value);
    if (newNode == NULL) return;

    // 标准双链表插入逻辑
    newNode->next = cur->next;
    newNode->pre = cur;
    if (cur->next != NULL) {
        cur->next->pre = newNode;
    }
    cur->next = newNode;
}

// 删除某个节点
void delByPos(link head, int pos) {
    if (pos < 1 || head == NULL || head->next == NULL) return;
    link cur = head->next;
    int idx = 1;
    while (cur != NULL && idx < pos) {
        cur = cur->next;
        idx++;
    }
    if (cur == NULL) return;
    if (cur->pre != NULL) {
        cur->pre->next = cur->next;
    }
    if (cur->next != NULL) {
        cur->next->pre = cur->pre;
    }
    free(cur);
}

int main() {
    link head = NULL;
    initNode (&head);
    insertByPos(head, 1, 1);
    insertByPos(head, 2, 2);
    // insertTail(head,4);
    insertByPos(head, 3, 3);
    insertByPos(head, 5, 5);
    delByPos(head,2);
    printList(head);

    return 0;
}